package com.ssyt.store.sys.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.ssyt.store.common.BaseDao;
import com.ssyt.store.common.util.StringUtil;
import com.ssyt.store.sys.dao.StoreReceiveAddressDao;
import com.ssyt.store.sys.entity.StoreReceiveAddress;

@Repository
public class StoreReceiveAddressDaoImpl extends BaseDao<StoreReceiveAddress, String> implements StoreReceiveAddressDao {

	@Override
	public List<StoreReceiveAddress> getAddressByUserId(String userId) {
		String hql = "FROM StoreReceiveAddress WHERE sysUserId=? AND state IN(0,1)";
		List<StoreReceiveAddress> addresses = new ArrayList<StoreReceiveAddress>();
		addresses = listEntityByHql(hql, userId);
		return addresses;
	}

	@Override
	public void addStoreReceiveAddress(StoreReceiveAddress address) {
		save(address);
	}

	@Override
	public void deleteStoreReceiveAddress(String id) {
		delete(get(id));
	}
	
	
	@Override
	public StoreReceiveAddress getAddressById(String Id) {
		return get(Id);
	}

	@Override
	public StoreReceiveAddress getUserDefualtAddress(String userId) {
		String hql = "FROM StoreReceiveAddress WHERE sysUserId=? AND state=0";
		StoreReceiveAddress storeReceiveAddress = uniqueEntityByHql(hql, userId);
		if(storeReceiveAddress == null){
			List<StoreReceiveAddress> addresses = getAddressByUserId(userId);
			if(!addresses.isEmpty()){
				storeReceiveAddress = getAddressByUserId(userId).get(0);
			}
		}
		return storeReceiveAddress;
	}

	@Override
	public void saveOrUpdateAddress(StoreReceiveAddress storeReceiveAddress) {
		String id = storeReceiveAddress.getId();
		if(StringUtil.isNotEmpty(id)){
			update(storeReceiveAddress);
		}else{
			save(storeReceiveAddress);
		}
	}

	@Override
	public void useAddressToDefault(String Id, String userId) {
		List<StoreReceiveAddress> allAddresses = listEntityByHql("FROM StoreReceiveAddress WHERE sysUserId=? AND state IN(0,1)", userId);
		for (StoreReceiveAddress storeReceiveAddress : allAddresses) {
			storeReceiveAddress.setState((byte)1);
			update(storeReceiveAddress);
		}
		StoreReceiveAddress theStoreReceiveAddress = get(Id);
		theStoreReceiveAddress.setState((byte)0);
		update(theStoreReceiveAddress);
	}

}
